package com.yue.spdatasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.yue.spdatasource.datasource.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 1 创建两个数据源primary和second
 * 2 创建一个动态数据源,把primary和second放到map里
 * 3 创建一个DsType的annotation，DsType放到方法或类上指定数据源
 * 4 创建DsType的切面，通过切面自动切换数据源
 */

@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DruidDataSource dataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix="spring.datasource.second")
    public DruidDataSource dataSource2(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource dataSource,DataSource dataSource2)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("primary", dataSource);
        targetDataSources.put("second", dataSource2);
        return new DynamicDataSource(dataSource, targetDataSources);
    }
}
